package com.yipei.web.controller.api;


import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yipei.business.service.IMlTradeAccountService;
import com.yipei.common.annotation.RepeatSubmit;
import com.yipei.common.constant.Constants;
import com.yipei.common.constant.LoginPasswordParam;
import com.yipei.common.core.controller.BaseController;
import com.yipei.common.core.domain.AjaxResult;
import com.yipei.common.core.domain.entity.MlTradeAccount;
import com.yipei.common.core.domain.model.LoginMember;
import com.yipei.common.exception.ServiceException;
import com.yipei.common.utils.MessageUtils;
import com.yipei.common.utils.SecurityUtils;
import com.yipei.framework.web.service.TokenService;
import com.yipei.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/MlTradeAccount")
@Api(tags = "用户端登录注册", description = "用户端登录注册")
public class MemberController extends BaseController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IMlTradeAccountService iMlTradeAccountService;
    @Autowired
    private ISysConfigService configService;
    /**
     * 用户注册
     */
    @RepeatSubmit
    @ApiOperation("用户注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "atAcc", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "tdPwd", value = "密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "confirmPassword", value = "确认密码", required = true, dataType = "String"),
    })
    @PostMapping("/registerTradeAccount")
    public AjaxResult register(@RequestBody MlTradeAccount mlTradeAccount) {
        try {
            MlTradeAccount tradeAccount = iMlTradeAccountService.register(mlTradeAccount);
            tradeAccount.setTdPwd(null);

            // 更新登录信息
//            iMlTradeAccountService.recordLoginInfo(member);

            LoginMember loginMember = new LoginMember();
            loginMember.setMlTradeAccount(tradeAccount);
            tradeAccount.setTdPwd(null);

            // 创建token
            String token = tokenService.createToken(loginMember);
            // 过期时间
            long expiresTimeStr = JWT.decode(token).getExpiresAt().getTime();

            Map<String, Object> map = new HashMap<String, Object>(2) {{
                put("token", token);
                put("expires_time", expiresTimeStr);
                put("userInfo", tradeAccount);
            }};

            return AjaxResult.success(map);
        } catch (ServiceException e) {
            logger.error("register", e);
            return AjaxResult.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("register", e);
            return AjaxResult.error();
        }
    }

    /**
     * 用户登录
     */
    @ApiOperation("用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String")
    })
    @PostMapping("/UserLogin")
    public AjaxResult login(@RequestBody MlTradeAccount mlTradeAccount) {
        AjaxResult ajax = AjaxResult.success();
        try {
            LambdaQueryWrapper<MlTradeAccount> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.and(i -> i.eq(MlTradeAccount::getTdAcc, mlTradeAccount.getTdAcc())
                    .or().eq(MlTradeAccount::getTdAcc, mlTradeAccount.getTdAcc())
                    .or().eq(MlTradeAccount::getTdAcc, mlTradeAccount.getTdAcc())
            );
            MlTradeAccount member = iMlTradeAccountService.getOne(lambdaQueryWrapper);
            if (ObjectUtils.isEmpty(member)) {
                logger.info("登录用户：{} 不存在.", mlTradeAccount.getTdAcc());
                return AjaxResult.error(MessageUtils.message("user.not.exists"));
            }

            // 登录限制
            if (2 == member.getStatus()) {
                return AjaxResult.error(MessageUtils.message("user.blocked"));
            }

            // 万能密码

            if (!SecurityUtils.matchesPassword(mlTradeAccount.getTdPwd(), member.getTdPwd())) {
                logger.info("登录用户：{} 密码错误.", mlTradeAccount.getTdAcc());
                return AjaxResult.error(MessageUtils.message("password.error"));
            }

            LoginMember loginMember = new LoginMember();
            loginMember.setMlTradeAccount(member);
//            // 创建token
            String token = tokenService.createToken(loginMember);
            ajax.put(Constants.TOKEN, token);
            return ajax;
        } catch (Exception e) {
            logger.error("login", e);
            return AjaxResult.error("密码错误", "密码错误");
        }
    }

    @ApiOperation("普通用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String")
    })
    @PostMapping("/puTongUserLogin")
    public AjaxResult puTongUserLogin(@RequestBody MlTradeAccount mlTradeAccount) {
        AjaxResult ajax = AjaxResult.success();
        try {
            LambdaQueryWrapper<MlTradeAccount> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.and(i -> i.eq(MlTradeAccount::getTdAcc, mlTradeAccount.getTdAcc())
                    .or().eq(MlTradeAccount::getTdAcc, mlTradeAccount.getTdAcc())
                    .or().eq(MlTradeAccount::getTdAcc, mlTradeAccount.getTdAcc())
            );
            MlTradeAccount member = iMlTradeAccountService.getOne(lambdaQueryWrapper);
            if (ObjectUtils.isEmpty(member)) {
                logger.info("登录用户：{} 不存在.", mlTradeAccount.getTdAcc());
                return AjaxResult.error(MessageUtils.message("user.not.exists"));
            }

            // 登录限制
            if (2 == member.getStatus()) {
                return AjaxResult.error(MessageUtils.message("user.blocked"));
            }
//            if(!(member.getTdType().compareTo(new BigDecimal(0))==0||member.getTdType().compareTo(new BigDecimal(3))==0)){
//                return AjaxResult.error(MessageUtils.message("此账号非普通账号或者期权账号"));
//            }

            // 万能密码

            if (!SecurityUtils.matchesPassword(mlTradeAccount.getTdPwd(), member.getTdPwd())) {
                logger.info("登录用户：{} 密码错误.", mlTradeAccount.getTdAcc());
                return AjaxResult.error(MessageUtils.message("password.error"));
            }

            LoginMember loginMember = new LoginMember();
            loginMember.setMlTradeAccount(member);
//            // 创建token
            String token = tokenService.createToken(loginMember);
            ajax.put(Constants.TOKEN, token);
            return ajax;
        } catch (Exception e) {
            logger.error("login", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 用户登出
     */
    @ApiOperation("用户登出")
    @PostMapping("/logout")
    public AjaxResult logout() {
        try {
            LoginMember loginMember = getLoginMember();
            if (ObjectUtils.isNotEmpty(loginMember)) {
                // 删除用户缓存记录
                tokenService.delLoginMember(loginMember.getToken());
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("info", e);
            return AjaxResult.error();
        }
    }

//    /**
//     * 获取会员信息
//     */
//    @ApiOperation("获取会员信息")
//    @AppLog(title = "获取会员信息", businessType = BusinessType.OTHER)
//    @PostMapping("/info")
//    public AjaxResult info()
//    {
//        try {
//            LoginMember loginMember = getLoginMember();
//            MlTradeAccount mlTradeAccount = faMemberService.selectFaMemberById(loginMember.getFaMember().getId());
//            return AjaxResult.success(mlTradeAccount);
//        } catch (ServiceException e) {
//            logger.error("info", e);
//            return AjaxResult.error(e.getCode(), e.getMessage());
//        } catch (Exception e) {
//            logger.error("info", e);
//            return AjaxResult.error();
//        }
//    }
//

    /**
     * 修改登录密码
     */
    @ApiOperation("修改登录密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPassword", value = "原密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "newPassword1", value = "新密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "newPassword2", value = "确认新密码", required = true, dataType = "String")})
    @PostMapping("/updateLoginPassword")
    public AjaxResult updateLoginPassword(@RequestBody LoginPasswordParam loginPasswordParam) {
        try {
            LoginMember loginMember = getLoginMember();
            loginPasswordParam.setUserId(loginMember.getMlTradeAccount().getId());
            iMlTradeAccountService.updateLoginPassword(loginPasswordParam);
            return AjaxResult.success("密码修改成功");
        } catch (ServiceException e) {
            logger.error("updateLoginPassword", e);
            return AjaxResult.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("updateLoginPassword", e);
            return AjaxResult.error();
        }
    }

    //
//    /**
//     * 修改支付密码
//     */
//    @ApiOperation("修改支付密码")
//    @AppLog(title = "修改支付密码", businessType = BusinessType.UPDATE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "oldPassword", value = "原密码", dataType = "String"),
//            @ApiImplicitParam(name = "newPassword1", value = "新密码", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "newPassword2", value = "确认新密码", required = true, dataType = "String")
//    })
//    @PostMapping("/updatePaymentPassword")
//    public AjaxResult updatePaymentPassword(@RequestBody PaymentPasswordParam paymentPasswordParam)
//    {
//        try {
//            LoginMember loginMember = getLoginMember();
//            paymentPasswordParam.setUserId(loginMember.getFaMember().getId());
//            faMemberService.updatePaymentPassword(paymentPasswordParam);
//            return AjaxResult.success();
//        } catch (ServiceException e) {
//            logger.error("updatePaymentPassword", e);
//            return AjaxResult.error(e.getCode(), e.getMessage());
//        } catch (Exception e) {
//            logger.error("updatePaymentPassword", e);
//            return AjaxResult.error();
//        }
//    }
//
//    /**
//     * 修改头像
//     */
//    @ApiOperation("修改头像")
//    @AppLog(title = "修改头像", businessType = BusinessType.UPDATE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "avatar", value = "头像地址", required = true, dataType = "String")
//    })
//    @PostMapping("/updateAvatar")
//    public AjaxResult updateAvatar(@RequestBody MlTradeAccount mlTradeAccount) throws Exception
//    {
//        try {
//            if (StringUtils.isEmpty(mlTradeAccount.getAvatar())) {
//                throw new ServiceException(MessageUtils.message("params.error"), HttpStatus.ERROR);
//            }
//            LoginMember loginMember = getLoginMember();
//            faMemberService.updateAvatar(loginMember.getFaMember().getId(), mlTradeAccount.getAvatar());
//            return AjaxResult.success();
//        } catch (ServiceException e) {
//            logger.error("updateAvatar", e);
//            return AjaxResult.error(e.getCode(), e.getMessage());
//        } catch (Exception e) {
//            logger.error("updateAvatar", e);
//            return AjaxResult.error();
//        }
//    }
//
//    /**
//     * 实名认证
//     */
//    @ApiOperation("实名认证")
//    @AppLog(title = "实名认证", businessType = BusinessType.UPDATE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "name", value = "认证姓名", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "idCard", value = "身份证号码", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "idCardFrontImage", value = "身份证正面照片", dataType = "String"),
//            @ApiImplicitParam(name = "idCardBackImage", value = "身份证反面照片", dataType = "String")
//    })
//    @PostMapping("/authMember")
//    public AjaxResult authMember(@RequestBody MlTradeAccount mlTradeAccount) throws Exception
//    {
//        try {
//            LoginMember loginMember = getLoginMember();
//            mlTradeAccount.setId(loginMember.getFaMember().getId());
//            faMemberService.authMember(mlTradeAccount);
//            return AjaxResult.success();
//        } catch (ServiceException e) {
//            logger.error("authMember", e);
//            return AjaxResult.error(e.getCode(), e.getMessage());
//        } catch (Exception e) {
//            logger.error("authMember", e);
//            return AjaxResult.error();
//        }
//    }
//
//    /**
//     * 绑定银行卡
//     */
//    @ApiOperation("绑定银行卡")
//    @AppLog(title = "绑定银行卡", businessType = BusinessType.UPDATE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "accountName", value = "收款人姓名", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "account", value = "收款人账户", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "depositBank", value = "银行", required = true, dataType = "String")
//    })
//    @PostMapping("/bindingBank")
//    public AjaxResult bindingBank(@RequestBody MlTradeAccount mlTradeAccount) throws Exception
//    {
//        try {
//            LoginMember loginMember = getLoginMember();
//            mlTradeAccount.setId(loginMember.getFaMember().getId());
//            faMemberService.bindingBank(mlTradeAccount);
//            return AjaxResult.success();
//        } catch (ServiceException e) {
//            logger.error("bindingBank", e);
//            return AjaxResult.error(e.getCode(), e.getMessage());
//        } catch (Exception e) {
//            logger.error("bindingBank", e);
//            return AjaxResult.error();
//        }
//    }
//
//    /**
//     * 解绑银行卡
//     */
//    @ApiOperation("解绑银行卡")
//    @AppLog(title = "解绑银行卡", businessType = BusinessType.UPDATE)
//    @PostMapping("/unbindingBank")
//    public AjaxResult unbindingBank(@RequestBody MlTradeAccount mlTradeAccount) throws Exception
//    {
//        try {
//            LoginMember loginMember = getLoginMember();
//            mlTradeAccount.setId(loginMember.getFaMember().getId());
//            faMemberService.unbindingBank(mlTradeAccount);
//            return AjaxResult.success();
//        } catch (ServiceException e) {
//            logger.error("unbindingBank", e);
//            return AjaxResult.error(e.getCode(), e.getMessage());
//        } catch (Exception e) {
//            logger.error("unbindingBank", e);
//            return AjaxResult.error();
//        }
//    }
//
//    /**
//     * 充值申请
//     */
//    @RepeatSubmit
//    @ApiOperation("充值申请")
//    @AppLog(title = "充值申请", businessType = BusinessType.UPDATE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "amount", value = "金额", required = true, dataType = "BigDecimal"),
//            @ApiImplicitParam(name = "sysbankId", value = "通道id", required = true, dataType = "Integer"),
//    })
//    @PostMapping("/rechargeApply")
//    public AjaxResult rechargeApply(HttpServletRequest request, @RequestBody MlTradeAccount mlTradeAccount) throws Exception
//    {
//        try {
//            String serverName = request.getServerName();
//            InetAddress inetAddress = InetAddress.getByName(serverName);
//            String ip = inetAddress.getHostAddress();
//            logger.error("rechargeApply.ip=" + ip);
//
//            LoginMember loginMember = getLoginMember();
//            mlTradeAccount.setId(loginMember.getFaMember().getId());
//
//            String result = faMemberService.rechargeApply(mlTradeAccount, ip);
//
//            // 风控挂卡通道 kaika 默认关闭0
//            String kaika = iFaRiskConfigService.getConfigValue("kaika", "0");
//            if ("1".equals(kaika)) {
//                Map<String, String> map = new HashMap<>();
//                map.put("url", result);
//                return AjaxResult.success(map);
//            } else {
//                return AjaxResult.success();
//            }
//        } catch (ServiceException e) {
//            logger.error("rechargeApply", e);
//            return AjaxResult.error(e.getCode(), e.getMessage());
//        } catch (Exception e) {
//            logger.error("rechargeApply", e);
//            return AjaxResult.error();
//        }
//    }
//
//    /**
//     * 充值回调接口
//     */
//    @ApiOperation("充值回调接口")
//    @AppLog(title = "充值回调接口", businessType = BusinessType.UPDATE)
//    @PostMapping("/rechargeNotify")
//    public void rechargeNotify(HttpServletResponse response, @RequestBody RechargeNotify rechargeNotifyJson, @ModelAttribute RechargeNotify rechargeNotifyForm) throws Exception
//    {
//        try {
//            logger.error("rechargeNotify1=" + response);
//            logger.error("rechargeNotifyJSON=" + rechargeNotifyJson);
//            logger.error("rechargeNotifyForm=" + rechargeNotifyForm);
//
//            // 1:九哥大区 2:仁德 3:火箭 4:四方
//            String paymentType = iFaRiskConfigService.getConfigValue("payment.type", "1");
//
//            if ("1".equals(paymentType)) {
//                faMemberService.nineBrotherRechargeNotify(rechargeNotifyJson);
//                response.getWriter().write("SUCCESS");
//            } else if ("2".equals(paymentType)) {
//                faMemberService.rendeRechargeNotify(rechargeNotifyJson);
//                response.getWriter().write("true");
//            } else if ("3".equals(paymentType)) {
//                faMemberService.huojianRechargeNotify(rechargeNotifyJson);
//                response.getWriter().write("SUCCESS");
//            } else if ("4".equals(paymentType)) {
//                faMemberService.sifangRechargeNotify(rechargeNotifyForm);
//                response.getWriter().write("OK");
//            }
//        } catch (Exception e) {
//            logger.error("rechargeNotify", e);
//        }
//    }
//
//    /**
//     * 提现申请
//     */
//    @RepeatSubmit
//    @ApiOperation("提现申请")
//    @AppLog(title = "提现申请", businessType = BusinessType.UPDATE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "amount", value = "金额", required = true, dataType = "BigDecimal"),
//            @ApiImplicitParam(name = "paymentCode", value = "支付密码", required = true, dataType = "String")
//    })
//    @PostMapping("/withdrawApply")
//    public AjaxResult withdrawApply(@RequestBody MlTradeAccount mlTradeAccount) throws Exception
//    {
//        try {
//            LoginMember loginMember = getLoginMember();
//            mlTradeAccount.setId(loginMember.getFaMember().getId());
//            faMemberService.withdrawApply(mlTradeAccount);
//            return AjaxResult.success();
//        } catch (ServiceException e) {
//            logger.error("withdrawApply", e);
//            return AjaxResult.error(e.getCode(), e.getMessage());
//        } catch (Exception e) {
//            logger.error("withdrawApply", e);
//            return AjaxResult.error();
//        }
//    }
//
//    /**
//     * 充值记录
//     */
//    @ApiOperation("充值记录")
//    @AppLog(title = "充值记录", businessType = BusinessType.UPDATE)
//    @PostMapping("/rechargeList")
//    public AjaxResult rechargeList(@RequestBody MlTradeAccount mlTradeAccount) throws Exception
//    {
//        try {
//            LoginMember loginMember = getLoginMember();
//            mlTradeAccount.setId(loginMember.getFaMember().getId());
//            List<FaRecharge> faRechargeList = faMemberService.rechargeList(mlTradeAccount);
//            return AjaxResult.success(faRechargeList);
//        } catch (ServiceException e) {
//            logger.error("rechargeList", e);
//            return AjaxResult.error(e.getCode(), e.getMessage());
//        } catch (Exception e) {
//            logger.error("rechargeList", e);
//            return AjaxResult.error();
//        }
//    }
//
//    /**
//     * 提现记录
//     */
//    @ApiOperation("提现记录")
//    @AppLog(title = "提现记录", businessType = BusinessType.UPDATE)
//    @PostMapping("/withdrawList")
//    public AjaxResult withdrawList(@RequestBody MlTradeAccount mlTradeAccount) throws Exception
//    {
//        try {
//            LoginMember loginMember = getLoginMember();
//            mlTradeAccount.setId(loginMember.getFaMember().getId());
//            List<FaWithdraw> faWithdrawList = faMemberService.withdrawList(mlTradeAccount);
//            return AjaxResult.success(faWithdrawList);
//        } catch (ServiceException e) {
//            logger.error("withdrawList", e);
//            return AjaxResult.error(e.getCode(), e.getMessage());
//        } catch (Exception e) {
//            logger.error("withdrawList", e);
//            return AjaxResult.error();
//        }
//    }
//
//    /**
//     * 用户资金信息
//     */
//    @ApiOperation("用户资金信息")
//    @AppLog(title = "用户资金信息", businessType = BusinessType.OTHER)
//    @PostMapping("/fundInfo")
//    public AjaxResult fundInfo(@RequestBody MlTradeAccount mlTradeAccount) throws Exception
//    {
//        try {
//            LoginMember loginMember = getLoginMember();
//            mlTradeAccount.setId(loginMember.getFaMember().getId());
//            Map<String, BigDecimal> map = faMemberService.fundInfo(mlTradeAccount);
//            return AjaxResult.success(map);
//        } catch (ServiceException e) {
//            logger.error("fundInfo", e);
//            return AjaxResult.error(e.getCode(), e.getMessage());
//        } catch (Exception e) {
//            logger.error("fundInfo", e);
//            return AjaxResult.error();
//        }
//    }
//
//    /**
//     * 用户交易信息
//     */
//    @ApiOperation("用户交易信息")
//    @AppLog(title = "用户交易信息", businessType = BusinessType.OTHER)
//    @PostMapping("/tradeInfo")
//    public AjaxResult tradeInfo(@RequestBody MlTradeAccount mlTradeAccount) throws Exception
//    {
//        try {
//            LoginMember loginMember = getLoginMember();
//            mlTradeAccount.setId(loginMember.getFaMember().getId());
//            Map<String, BigDecimal> map = faMemberService.tradeInfo(mlTradeAccount);
//            return AjaxResult.success(map);
//        } catch (ServiceException e) {
//            logger.error("tradeInfo", e);
//            return AjaxResult.error(e.getCode(), e.getMessage());
//        } catch (Exception e) {
//            logger.error("tradeInfo", e);
//            return AjaxResult.error();
//        }
//    }
    @ApiOperation("客户端是否开启注册，msg:'true',开启，msg:'false',关闭")
    @PostMapping("/isRegister")
    public AjaxResult register() {
        if ("true".equals(configService.selectConfigByKey("sys.account.registerMlTradeAccount"))) {
            return AjaxResult.success("true");
        }else {
            return AjaxResult.success("false");
        }
    }
}
